package com.htiiot.status.hdfs;

import com.htiiot.status.config.Configs;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public abstract class HTWriter {

	protected String filePath;
	protected OutputStream os;
	private long tid;
	private String host;
	private long time;
	private boolean opened = true;

	protected void createFile(File file, boolean isDec) throws IOException {

		if (!file.getParentFile().exists()) {
			createFile(file.getParentFile(), true);
		} else {
			// 是否是文件夹
			if (isDec) {
				file.mkdir();
			} else {
				file.createNewFile();
			}
		}
	}

	public HTWriter(long tID, String host, long time) throws IOException {
		this.tid = tID;
		this.host = host;
		this.time = time;
		SimpleDateFormat sf = new SimpleDateFormat("yyyy/MM/dd");
		String date = sf.format(Calendar.getInstance().getTime());
		this.filePath = Configs.WriteConfig.BASE_PATH + "/devicestatus/" + date + "/tid_" + tID + "/host_" + host + "_ts_" + time;
		this.opened = true;
		new Thread(new FlushThread()).start();
	}

	public void write(String data) throws IOException {
		os.write(data.getBytes());
	}

	public abstract void flush();

	public void close() {
		opened = false;
		try {
			os.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}
	public String getFile() {
		return filePath;
	}

	public long getTid() {
		return tid;
	}

	public long getTime() {
		return time;
	}

	class FlushThread implements Runnable {

		@Override
		public void run() {
			// 第一次执行时等待10S
			try {
				Thread.sleep(10000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			while (opened) {
				flush();
				try {
					Thread.sleep(10000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

			}

		}

	}

}
